package com.mgxy;


import javax.swing.*;
import java.awt.*;


public class BallGame extends  JFrame {
    /** 双缓存解决闪动问题 */
    Image offScreenImage = null;
    //获得桌面的对象
    DeskComponent desk = new DeskComponent();
    //定义白球
    BallComponent ballWhite = new BallComponent("ballWhite",200,200,0,Math.PI/3,this);
    DirectionComponent directionComponent = new DirectionComponent(this,ballWhite);

    int a= 1;
    public BallGame(){
        //为白球添加图片
        ballWhite.setBallimg("imgs/ball.png");
    }

    /** 窗口创建启动方法 */
    public void launch(){
        //设置窗口大小
        setSize(856,501);
        //设置窗口的位置
        setLocation(100,200);
        //设置窗口标题
        setTitle("桌球小游戏----By MG斜阳");
        //设置关闭事件
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //设置窗口是否可见
        setVisible(true);

        while (true){
            repaint();
            try {
                //暂停40毫秒，相当于1秒钟执行(1000/40 = 25)次 repaint()方法
                Thread.sleep(40);
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void paint(Graphics g){
        /** 创建和容器一样大小的Image图片 */
        if(offScreenImage ==null){
            offScreenImage=this.createImage(856, 501);
        }
        /** 获得该图片的画布*/
        Graphics gImage= offScreenImage.getGraphics();
        /** 填充整个画布*/
        gImage.fillRect(0, 0, 856, 501);
        //绘制台球桌面
        desk.paintSelf(gImage);
        //绘制白球
        ballWhite.paintSelf(gImage);
        //改变画笔颜色
        gImage.setColor(Color.RED);
        //画红线
            gImage.drawLine((int) directionComponent.getStart_x(),(int)directionComponent.getStart_y(),
                    (int)directionComponent.getEnd_x(),(int)directionComponent.getEnd_y());
        /** 将缓冲区绘制好哦的图形整个绘制到容器的画布中 */
        g.drawImage(offScreenImage, 0, 0, null);
    }



    public static void main(String[] args) {
        BallGame bg = new BallGame();
        bg.launch();
    }

}
